package com.qls.consumer.biz.config;

import com.qls.consumer.biz.service.OpTaskStatusService;
import com.qls.core.dto.InitBody;
import com.qls.core.dto.PushRatesBody;
import com.qls.core.dto.PushRpBody;
import com.qls.core.entity.HtHotel;
import com.qls.mt.api.MtRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author doyoung
 */
@Slf4j
@Component
public class ReceiveHandlerBasic {

    @Autowired
    private OpTaskStatusService opTaskStatusService;

    @Autowired
    private MtRemoteService mtRemoteService;

    @RabbitListener(queues = "INIT", containerFactory = "initContainerFactory")
    public void init(InitBody msg) {
        Integer taskId = msg.getTaskId();
        Long hotelId = msg.getHotelId();
        this.add(taskId, hotelId);
        this.over(hotelId, taskId);
        if (hotelId.equals(-1L)) {
            return;
        }
        try {
            mtRemoteService.hotelDetail(msg);
        } catch (Exception e) {
            log.error("酒店id：" + hotelId + "酒店初始化失败" + e.getMessage());
        }
    }

    @RabbitListener(queues = "CALLBACK_RATES", containerFactory = "callbackRates")
    public void callbackRates(PushRatesBody msg) {
        mtRemoteService.callbackRates(msg);
    }

    @RabbitListener(queues = "CALLBACK_RP", containerFactory = "callbackRp")
    public void callbackRp(PushRpBody pushRpBody) {
        mtRemoteService.callbackRp(pushRpBody);
    }

    @RabbitListener(queues = "CALLBACK_HOTEL", containerFactory = "callbackHotel")
    public void callbackHotel(HtHotel msg) {
        mtRemoteService.callbackHotel(msg);
    }


    /**
     * 增加任务数量
     *
     * @param taskCode Integer
     */
    private void add(Integer taskCode, Long code) {
        if (Objects.isNull(taskCode) || code.equals(-1L)) {
            return;
        }
        opTaskStatusService.completedAdd(taskCode, 1);
    }

    /**
     * 结束任务
     *
     * @param code     Long
     * @param taskCode Integer
     */
    private void over(Long code, Integer taskCode) {
        if (Objects.nonNull(taskCode) && code.equals(-1L)) {
            opTaskStatusService.updateByTaskCode(taskCode, new Date());
        }
    }


}
